<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息</h2>
          <el-button type="primary" @click="handleEdit">编辑资料</el-button>
        </div>
      </template>
      
      <div class="profile-content">
        <div class="avatar-section">
          <img :src="userInfo.avatar" class="avatar" alt="用户头像" />
          <h3>{{ userInfo.username }}</h3>
        </div>
        
        <div class="info-section">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ userInfo.fullName }}</el-descriptions-item>
            <el-descriptions-item label="角色">{{ userInfo.role }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ userInfo.createTime }}</el-descriptions-item>
            <el-descriptions-item label="消息订阅">
              <div class="subscribe-settings">
                <el-switch
                  v-model="subscribeSettings.subscribeWeb"
                  active-text="网页通知"
                  @change="handleSubscribeChange('web')"
                />
                <el-switch
                  v-model="subscribeSettings.subscribeWechat"
                  active-text="微信通知"
                  @change="handleSubscribeChange('wechat')"
                  style="margin-left: 20px"
                />
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑个人信息" v-model="dialogVisible" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editForm.fullName" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getUserSubscribe, createUserSubscribe, updateUserSubscribe } from '../api/userSubscribe'

const userInfo = reactive({
  username: '',
  fullName: '',
  role: '',
  email: '',
  phone: '',
  avatar: '',
  createTime: ''
})

const dialogVisible = ref(false)
const editForm = reactive({
  fullName: '',
  email: '',
  phone: '',
  avatar: ''
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 这里应该调用后端API获取用户信息
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      const parsedUser = JSON.parse(storedUser)
      Object.assign(userInfo, parsedUser)
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 打开编辑对话框
const handleEdit = () => {
  Object.assign(editForm, userInfo)
  dialogVisible.value = true
}

// 保存编辑后的信息
const handleSave = async () => {
  try {
    // 这里应该调用后端API保存用户信息
    Object.assign(userInfo, editForm)
    ElMessage.success('保存成功')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 头像上传成功回调
const handleAvatarSuccess = (response) => {
  editForm.avatar = response.url
}

const subscribeSettings = reactive({
  subscribeWeb: false,
  subscribeWechat: false
})

// 获取用户订阅设置
const fetchUserSubscribe = async () => {
  try {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      const parsedUser = JSON.parse(storedUser)
      const response = await getUserSubscribe(parsedUser.id)
      if (response && response.subscribe) {
        subscribeSettings.subscribeWeb = response.subscribe.subscribe_web
        subscribeSettings.subscribeWechat = response.subscribe.subscribe_wechat
      }
    }
  } catch (error) {
    console.error('获取订阅设置失败:', error)
  }
}

// 处理订阅变更
const handleSubscribeChange = async (type) => {
  try {
    const storedUser = localStorage.getItem('user')
    if (!storedUser) {
      ElMessage.error('请先登录')
      return
    }

    const parsedUser = JSON.parse(storedUser)
    const userId = parsedUser.id

    const subscribeData = {
      user_id: userId,
      subscribe_web: subscribeSettings.subscribeWeb,
      subscribe_wechat: subscribeSettings.subscribeWechat
    }

    // 尝试更新，如果失败则创建新的订阅设置
    try {
      await updateUserSubscribe(userId, subscribeData)
      ElMessage.success(`${type === 'web' ? '网页' : '微信'}通知设置已更新`)
    } catch (error) {
      // 如果更新失败，尝试创建
      await createUserSubscribe(subscribeData)
      ElMessage.success(`${type === 'web' ? '网页' : '微信'}通知设置已创建`)
    }
  } catch (error) {
    console.error('更新订阅设置失败:', error)
    ElMessage.error('更新订阅设置失败')
  }
}

onMounted(() => {
  fetchUserInfo()
  fetchUserSubscribe()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 15px;
}

.info-section {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.subscribe-settings {
  display: flex;
  align-items: center;
}
</style>